const log = require('../util/log')

module.exports = (req, res) => {
  require('../util/service').handlePost(req, res, (reqObj, resolve) => {
    const mongoMng = require('../mng/mongoMng')
    if (!mongoMng.db) {
      log('未连接mongo')
      resolve({
        result: -1,
        msg: '系统错误'
      })
      return;
    }
    if (!reqObj.password) {
      resolve({
        result: -1,
        msg: '缺少password'
      })
      return
    }
    mongoMng.db.collection('user').find({
      phone: req.session.customer.phone
    }).toArray((err, result) => {
      if (err) {
        log(err);
        resolve({
          result: -1,
          msg: '系统错误'
        })
        return;
      }
      if (result.length == 0) {
        mongoMng.db.collection('user').insert({
          phone: req.session.customer.phone,
          password: reqObj.password
        }, (err, result) => {
          if (err) {
            log(err);
            resolve({
              result: -1,
              msg: '系统错误'
            })
            return;
          }
          resolve({
            result: 1
          })
        });
      } else {
        mongoMng.db.collection('user').update({
          phone: req.session.customer.phone
        }, {
          $set: {
            password: reqObj.password
          }
        }, {
          multi: true
        }, (err, result) => {
          if (err) {
            log(err);
            resolve({
              result: -1,
              msg: '系统错误'
            })
            return;
          }
          resolve({
            result: 1
          })
        });
      }
    });
  })
}
